<template>
  <div class="app-container">
    <div class="filter-container" style="padding-bottom: 20px;text-align: right;">
      <el-button class="filter-item" style="margin-left: 10px;" @click="$router.push('/admin/add')" type="primary" icon="el-icon-edit" v-if="hasPower('/admin/add')">添加管理员</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleRemove()" type="danger" icon="el-icon-edit" v-if="hasPower('/admin/remove')">删除</el-button>
    </div>
    <div class="filter-container" style="padding-bottom: 20px;">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="请输入管理员名" v-model="listQuery.username">
      </el-input>
      <el-select @change='handleFilter' placeholder="全部" style="width: 140px" class="filter-item" v-model="listQuery.status">
        <el-option v-for="item in opts.status" :key="item.key" :label="item.label" :value="item.key">
        </el-option>
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-reset" @click="handleReset">重置</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="fetchData">搜索</el-button>
    </div>
    <el-table :data="data.list" v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50">
      </el-table-column>
      <el-table-column type="index" label="序号" width="50">
      </el-table-column>
      <el-table-column label="用户名" width="160">
        <template slot-scope="scope">
          {{scope.row.username}}
        </template>
      </el-table-column>
      <el-table-column label="手机号" width="120">
        <template slot-scope="scope">
          <span>{{scope.row.mobile}}</span>
        </template>
      </el-table-column>
      <el-table-column label="邮箱" width="200">
        <template slot-scope="scope">
          <span>{{scope.row.mail}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="加入时间" width="180">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span>{{Acan.ObjectIdParse(scope.row._id).date}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="最后登录时间" width="180">
        <template slot-scope="scope" v-if="scope.row.last">
          <i class="el-icon-time"></i>
          <span>{{scope.row.last.login}}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后登录IP" width="140">
        <template slot-scope="scope" v-if="scope.row.last">
          {{scope.row.last.ip}}
        </template>
      </el-table-column>
      <el-table-column label="角色" width="110">
        <template slot-scope="scope">
          {{roles[scope.row.role]}}
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="状态" width="80" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | statusFilter">{{scope.row.status === 0 ? '正常' : '冻结'}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="操作" min-width="300">
        <template slot-scope="scope">
          <el-button type="" size="mini" @click="handleRoleOpen(scope.row)" v-if="hasPower('adminPower')">角色</el-button>
          <el-button type="" size="mini" @click="$router.push({path: '/log/admin', query: {opuser: scope.row._id, opname: scope.row.username}})" v-if="hasPower('logAdmin')">日志</el-button>
          <el-button type="primary" size="mini" @click="$router.push({path: '/admin/edit', query: {_id: scope.row._id}})" v-if="hasPower('/admin/edit')">编辑</el-button>
          <el-button type="danger" size="mini" @click="handleRemove(scope.row)" v-if="hasPower('/admin/remove')">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      style="margin-top:30px;"
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="data.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="data.limit"
      layout="total, sizes, prev, pager, next, jumper"
      :total="data.total">
    </el-pagination>

    <el-dialog title="选择角色" :visible.sync="dialogRole">
      <div class="">
        <el-radio-group v-model="edit.role" style="padding: 20px 0;">
          <el-radio v-for="(o, i) in roles" :key="i" :label="i">{{o}}</el-radio>
        </el-radio-group>
      </div>
      <el-button type="success" @click="handleRoleUp">确定</el-button>
    </el-dialog>
  </div>

</template>

<script>
import { getList, postOne as adminUp, remove } from '@/api/admin'
import { getOpt } from '@/api/role'

export default {
  data() {
    return {
      data: {
        limit: 10,
        total: 0,
        page: 1
      },
      listQuery: {},
      listSelect: [],
      dialogRole: false,
      edit: {},
      roles: {},
      opts: {
        status: [
          {
            key: '', label: '全部'
          },
          {
            key: 0, label: '正常'
          },
          {
            key: -1, label: '冻结'
          }
        ]
      },
      listLoading: true
    }
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: 'success',
        '-1': 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  watch: {
    '$route.query.role': function(val) {
      if (!val) delete this.listQuery.role
      else this.listQuery.role = val
      this.fetchData()
    }
  },
  created() {
    if (this.$route.query.role) this.listQuery.role = this.$route.query.role
    this.fetchData()
    getOpt(opt => {
      this.roles = opt
    })
  },
  methods: {
    handleRoleOpen(o) {
      this.dialogRole = true
      this.editOld = o
      this.edit = Object.assign({}, o)
    },
    handleRoleUp() {
      adminUp({
        _id: this.edit._id
      }, {
        role: this.edit.role
      }).then(response => {
        if (response.code === 30000) {
          this.$message({
            type: 'success',
            message: '更新成功!'
          })
          this.editOld.role = this.edit.role
          this.dialogRole = false
        } else {
          this.$message({
            type: 'info',
            message: '更新失败!'
          })
        }
      })
    },
    handleReset() {
      delete this.listQuery.status
      delete this.listQuery.username
      this.$forceUpdate()
    },
    handleSelectionChange(val) {
      this.listSelect = val
    },
    handleRemove(o) {
      var _ids = []
      this.listSelect.forEach((v) => {
        _ids.push(v._id)
      })
      if (o) {
        _ids = [o._id]
      }
      if (_ids.length < 1) {
        return this.$message({
          type: 'info',
          message: '请选择需要删除的管理员!'
        })
      }
      this.$confirm('确认继续删除选中的管理员?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log(_ids)
        remove({
          _id: _ids
        }).then(res => {
          if (res.code !== 30000) {
            return this.$message({
              type: 'error',
              message: '请求失败'
            })
          }
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.fetchData()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleFilter() {
      this.fetchData()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.fetchData()
    },
    fetchData(con) {
      if (this.listQuery.status === '') delete this.listQuery.status
      if (this.listQuery.username === '') delete this.listQuery.username
      this.listLoading = true
      getList(this.listQuery).then(response => {
        for (var i in response.data) {
          this[i] = response.data[i]
        }
        this.data = response.data
        this.listLoading = false
      })
    }
  }
}
</script>
